// @ts-ignore
import MarkdownIt from 'markdown-it'
// @ts-ignore
import MarkdownItContainer from 'markdown-it-container'
// @ts-ignore
// import MarkdownItAttrs from 'markdown-it-attrs'
import MarkdownItEmoji from 'markdown-it-emoji'
import fullEmoji from 'markdown-it-emoji/lib/data/full.json'
import hljs from 'highlight.js'

const md = new MarkdownIt({
  html: true,
  linkify: true,
  typographer: true,
  xhtmlOut: true,
  // breaks: true,
  // 我们在下面手动定义了 highlight, 故不用这里再定义 langPrefix
  // langPrefix: 'hljs language-', //默认为language-

  highlight: function (str: string, lang: string) {
    if (lang && hljs.getLanguage(lang)) {
      try {
        /*
          给每一行 fenced blocks 里写的代码 包裹一层li
          并给 fenced blocks 里的整个内容包裹一层ul
        */
        const enhanced = "<ul><li>"
          + hljs.highlight(str, {
            language: lang,
            ignoreIllegals: true
          }).value
            .replace(/(\n)$/, '') //fenced blocks语法原因,总是会多一个\n
            .replace(/\n/g, "\n</li><li>")
          + "\n</li></ul>";
        return `<pre><code class="hljs lang-${lang}">${enhanced}</code></pre>`
      } catch (err) {
        console.error(`something wrong with hljs.highlight:`, err);
      }
    }

    return `<pre><code class="hljs">${md.utils.escapeHtml(str)}</code></pre>`;
  }

})

/**
 * 自定义代码块
 */
const blocks = [
  {tag: 'tip', title: '提示'},
  {tag: 'success', title: '提示'},
  {tag: 'warn', title: '注意'},
  {tag: 'error', title: '注意'},
];

blocks.forEach(block => {
  md.use(MarkdownItContainer, block.tag, {
    render(tokens: any[], idx: number) {
      const token = tokens[idx]
      if (token.nesting === 1) {
        // opening tag
        let [tag, title] = token.info.trim().split(' ')
        title = title || block.title
        return `<div class="${block.tag} custom-block"> <p class="block-title">${title}</p>`;
      } else {
        // closing tag
        return '</div>\n';
      }
    },
  })
})

// md.use(MarkdownItAttrs, {});
md.use(MarkdownItEmoji)

md.renderer.rules.emoji = function (token: string, idx: number) {
  // @ts-ignore
  return `<span class="emoji emoji_${token[idx].markup}">${fullEmoji[token[idx].markup]}</span>`; //---> <span class="emoji emoji_baby_chick">🐤</span>
};

export function renderMarkdown(markdownString: string | undefined, el: HTMLElement): void {
  const innerHtml = !!markdownString ? md.render(markdownString) : null
  el.innerHTML = innerHtml;
}
